<template>
  <div class="sql-query-container">
    <h2>SQL查询界面测试</h2>
    
    <!-- 测试API连接 -->
    <div class="test-section">
      <h3>API连接测试</h3>
      <el-button @click="testAPI" :loading="testing">测试API连接</el-button>
      <div v-if="apiResult" class="result">
        <pre>{{ apiResult }}</pre>
      </div>
    </div>

    <!-- 数据库列表 -->
    <div class="test-section">
      <h3>数据库实例列表</h3>
      <el-button @click="loadDatabases" :loading="loading">加载数据库列表</el-button>
      <div v-if="databases.length > 0" class="database-list">
        <div v-for="db in databases" :key="db.id" class="database-item">
          <strong>{{ db.name }}</strong> ({{ db.database_type }})
          <br>
          <small>{{ db.host }}:{{ db.port }}</small>
          <span v-if="db.database_name"> / {{ db.database_name }}</span>
        </div>
      </div>
    </div>

    <!-- SQL查询测试 -->
    <div class="test-section" v-if="databases.length > 0">
      <h3>SQL查询测试</h3>
      <el-select v-model="selectedDatabase" placeholder="选择数据库">
        <el-option 
          v-for="db in availableDatabases" 
          :key="db.id" 
          :label="db.name" 
          :value="db.id"
        />
      </el-select>
      <br><br>
      <el-input 
        v-model="sqlContent" 
        type="textarea" 
        placeholder="输入SQL语句"
        :rows="4"
      />
      <br><br>
      <el-button 
        @click="executeQuery" 
        :loading="executing"
        :disabled="!selectedDatabase || !sqlContent.trim()"
        type="primary"
      >
        执行查询
      </el-button>
      
      <div v-if="queryResult" class="result">
        <h4>查询结果</h4>
        <p>执行时间: {{ queryResult.execution_time }}s</p>
        <p>返回行数: {{ queryResult.row_count }}</p>
        <p>SQL类型: {{ queryResult.sql_type }}</p>
        <div v-if="queryResult.rows && queryResult.rows.length > 0">
          <table border="1">
            <thead>
              <tr>
                <th v-for="(col, index) in queryResult.columns" :key="index">
                  {{ col }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, index) in queryResult.rows.slice(0, 10)" :key="index">
                <td v-for="(cell, cellIndex) in row" :key="cellIndex">
                  {{ cell }}
                </td>
              </tr>
            </tbody>
          </table>
          <p v-if="queryResult.rows.length > 10">
            ... 还有 {{ queryResult.rows.length - 10 }} 行数据
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { sqlAPI } from '@/api/sql'

// 响应式数据
const testing = ref(false)
const loading = ref(false)
const executing = ref(false)
const apiResult = ref('')
const databases = ref([])
const selectedDatabase = ref(null)
const sqlContent = ref('SHOW TABLES')
const queryResult = ref(null)

// 计算属性
const availableDatabases = computed(() => {
  return databases.value.filter(db => {
    // 过滤掉MySQL没有数据库名称的实例
    if (db.database_type === 'mysql' && !db.database_name) {
      return false
    }
    return true
  })
})

// 测试API连接
const testAPI = async () => {
  testing.value = true
  try {
    const response = await sqlAPI.getDatabaseInstances()
    apiResult.value = JSON.stringify(response, null, 2)
    ElMessage.success('API连接测试成功')
  } catch (error) {
    apiResult.value = `错误: ${error.message}`
    ElMessage.error('API连接测试失败')
  } finally {
    testing.value = false
  }
}

// 加载数据库列表
const loadDatabases = async () => {
  loading.value = true
  try {
    const response = await sqlAPI.getDatabaseInstances()
    console.log('API响应:', response)
    
    // 处理不同的响应格式
    let data = []
    if (response) {
      if (response.results) {
        data = response.results
      } else if (Array.isArray(response)) {
        data = response
      } else if (response.data && Array.isArray(response.data)) {
        data = response.data
      }
    }
    
    databases.value = data
    ElMessage.success(`成功加载 ${data.length} 个数据库实例`)
  } catch (error) {
    console.error('加载数据库失败:', error)
    ElMessage.error(`加载数据库失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 执行查询
const executeQuery = async () => {
  if (!selectedDatabase.value || !sqlContent.value.trim()) {
    ElMessage.warning('请选择数据库并输入SQL语句')
    return
  }

  executing.value = true
  try {
    const response = await sqlAPI.executeQuery({
      database_id: selectedDatabase.value,
      sql_content: sqlContent.value,
      limit: 1000
    })

    console.log('查询响应:', response)

    if (response && response.result) {
      queryResult.value = response.result
      ElMessage.success(response.message || '查询执行成功')
    } else {
      throw new Error('响应数据格式错误')
    }
  } catch (error) {
    console.error('查询执行失败:', error)
    
    let errorMessage = '查询执行失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    } else if (error.error) {
      errorMessage = error.error
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
    queryResult.value = null
  } finally {
    executing.value = false
  }
}
</script>

<style scoped>
.sql-query-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.test-section h3 {
  margin-top: 0;
  color: #303133;
}

.database-list {
  margin-top: 15px;
}

.database-item {
  padding: 10px;
  margin-bottom: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.result {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  max-height: 400px;
  overflow-y: auto;
}

.result pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

th, td {
  padding: 8px;
  text-align: left;
  border: 1px solid #ddd;
}

th {
  background-color: #f2f2f2;
  font-weight: bold;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}
</style>
